package mongox

import (
	"gitee.com/burningsong/golib/pkg/sqlex"
	"go.mongodb.org/mongo-driver/bson"
)

func OrderBy(items []sqlex.OrderItem) bson.D {
	result := bson.D{}
	size := len(items)
	if size == 0 {
		return bson.D{bson.E{Key: "_id", Value: -1}}
	}

	for _, v := range items {
		result = append(result, getOrderItemSort(v))
	}
	return result
}

func getOrderItemSort(v sqlex.OrderItem) bson.E {
	result := bson.E{
		Key:   v.Column,
		Value: 1,
	}

	if !v.Asc {
		result.Value = -1
	}
	return result
}

// generateSortField 生成aggregate用于排序的addFields,如下中的addFields的statusOrder值
/*
db.myCollection.aggregate([
  {
    $addFields: {
      statusOrder: {
        $switch: {
          branches: [
            { case: { $eq: ["$status", "unverified"] }, then: 1 },
            { case: { $eq: ["$status", "available"] }, then: 2 },
            { case: { $eq: ["$status", "error"] }, then: 3 }
          ],
          default: 4
        }
      }
    }
  },
  {
    $sort: {
      statusOrder: 1,   // 按 statusOrder 排序
      checkTime: -1     // 按 checkTime 倒序
    }
  },
  {
    $project: {
      statusOrder: 0   // 隐藏 statusOrder
    }
  }
])
*/
func generateAggSortField(info sqlex.OrderItem) bson.M {
	size := len(info.CustomOrderValues)
	branches := make([]bson.M, 0, size)
	for i, v := range info.CustomOrderValues {
		item := bson.M{
			"case": bson.M{
				"$eq": bson.A{
					"$" + info.Column,
					v,
				},
			},
			"then": i,
		}
		branches = append(branches, item)
	}

	return bson.M{
		"$switch": bson.M{
			"branches": branches,
			"default":  size,
		},
	}
}

// AggOrderBy 生成aggregate的排序信息,如下面数组的3组信息
/*
db.myCollection.aggregate([
  {
    $addFields: {
      statusOrder: {
        $switch: {
          branches: [
            { case: { $eq: ["$status", "unverified"] }, then: 1 },
            { case: { $eq: ["$status", "available"] }, then: 2 },
            { case: { $eq: ["$status", "error"] }, then: 3 }
          ],
          default: 4
        }
      }
    }
  },
  {
    $sort: {
      statusOrder: 1,   // 按 statusOrder 排序
      checkTime: -1     // 按 checkTime 倒序
    }
  },
  {
    $project: {
      statusOrder: 0   // 隐藏 statusOrder
    }
  }
])
*/
func AggOrderBy(items []sqlex.OrderItem) []bson.D {
	if len(items) == 0 {
		return nil
	}

	addFields := bson.D{}
	sortFields := bson.D{}
	hideCustomSortFields := bson.D{}

	// 遍历所有排序项
	for _, v := range items {
		if len(v.CustomOrderValues) == 0 {
			// 如果没有自定义排序值，直接添加到排序字段中
			sortFields = append(sortFields, getOrderItemSort(v))
		} else {
			// 自定义排序逻辑
			customSortField := "MY_" + v.Column
			sortFields = append(sortFields, bson.E{Key: customSortField, Value: 1})
			hideCustomSortFields = append(hideCustomSortFields, bson.E{Key: customSortField, Value: 0})
			addFields = append(addFields, bson.E{Key: customSortField, Value: generateAggSortField(v)})
		}
	}

	// 构建返回的聚合管道
	aggPipeline := []bson.D{}

	// 仅在有自定义字段的情况下添加 $addFields 阶段
	if len(addFields) > 0 {
		aggPipeline = append(aggPipeline, bson.D{{Key: "$addFields", Value: addFields}})
	}

	// 添加 $sort 阶段
	if len(sortFields) > 0 {
		aggPipeline = append(aggPipeline, bson.D{{Key: "$sort", Value: sortFields}})
	}

	// 仅在有隐藏字段时添加 $project 阶段
	if len(hideCustomSortFields) > 0 {
		aggPipeline = append(aggPipeline, bson.D{{Key: "$project", Value: hideCustomSortFields}})
	}

	return aggPipeline
}
